//
//  SAUserInfoManager.m
//  Shikamaru
//
//  Created by FangGeek on 2017/4/10.
//  Copyright © 2017年 FangGeek. All rights reserved.
//

#import "SAUserInfoManager.h"
#import "MJExtension.h"
#import "SARealmMessageModel.h"

#define kSAInfoKey @"SALoginInfo"
#define kSAnearInfoRsp @"nearInfoRsp"

#pragma mark - SAUserInfoModel
@implementation SAUserInfoModel
#pragma mark-------NSCoding,归接档协议,运行时

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    unsigned  int count = 0;
    Ivar *ivars = class_copyIvarList(self.class, &count);
    for (int i = 0; i < count; i++) {
        const char *cname = ivar_getName(ivars[i]);
        NSString *name = [NSString stringWithUTF8String:cname];
        NSString *key = [name substringFromIndex:1];
        id value = [self valueForKey:key];
        [aCoder encodeObject:value forKey:key];
    }
    
    ivars = class_copyIvarList(self.superclass, &count);
    for (int i = 0; i < count; i++) {
        const char *cname = ivar_getName(ivars[i]);
        NSString *name = [NSString stringWithUTF8String:cname];
        NSString *key = [name substringFromIndex:1];
        id value = [self valueForKey:key];
        [aCoder encodeObject:value forKey:key];
    }
    
    free(ivars);
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        
        unsigned  int count = 0;
        Ivar *ivars = class_copyIvarList(self.class, &count);
        
        for (int i = 0; i < count; i++) {
            const char *cname = ivar_getName(ivars[i]);
            NSString *name = [NSString stringWithUTF8String:cname];
            NSString *key = [name substringFromIndex:1];
            id value = [aDecoder decodeObjectForKey:key];
            if (value == nil)
            {
                continue;
            }
            [self setValue:value forKey:key];
        }
        
        ivars = class_copyIvarList(self.superclass, &count);
        
        for (int i = 0; i < count; i++) {
            const char *cname = ivar_getName(ivars[i]);
            NSString *name = [NSString stringWithUTF8String:cname];
            NSString *key = [name substringFromIndex:1];
            id value = [aDecoder decodeObjectForKey:key];
            if (value == nil)
            {
                continue;
            }
            [self setValue:value forKey:key];
        }
        
        free(ivars);
    }
    return self;
}

-(id)copyWithZone:(NSZone *)zone {
    id copy = [[[self class] allocWithZone:zone] init];
    unsigned  int count = 0;
    Ivar *ivars = class_copyIvarList(self.class, &count);
    
    for (int i = 0; i < count; i++) {
        const char *cname = ivar_getName(ivars[i]);
        NSString *name = [NSString stringWithUTF8String:cname];
        NSString *key = [name substringFromIndex:1];
        id value = [self valueForKey:key];
        [copy setValue:value forKey:key];
    }
    
    free(ivars);
    return copy;
}
@end

#pragma mark - SAUserInfoManager
@interface SAUserInfoManager()<EMChatManagerDelegate>
@end
@implementation SAUserInfoManager
//单例工厂方法
SASINGLETON_FOR_CLASS(SAUserInfoManager);

-(instancetype)init
{
    if (self = [super init])
    {
        self.model = [[SAUserInfoModel alloc] init];
        [self loadLoginInfo];
        
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Private Method


//读取个人信息
- (void)loadLoginInfo
{
    NSDictionary *dict = [[NSUserDefaults standardUserDefaults]objectForKey:kSAInfoKey];
    if (dict == nil) {
        return;
    }
    if (![dict isKindOfClass:[NSDictionary class]]) {
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:kSAInfoKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return;
    }
    self.model =  [SAUserInfoModel mj_objectWithKeyValues:dict];
    
}


- (void)cleanLoginInfo
{
    NSDictionary *dict = [[NSUserDefaults standardUserDefaults]objectForKey:kSAInfoKey];
    if (dict == nil) {
        return;
    }
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSAInfoKey];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SAShopId"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SAPhone"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    return;
}


#pragma mark Public Method

//存储个人信息
- (void)saveLoginInfo
{
    NSDictionary *dict = self.model.mj_keyValues;
    [[NSUserDefaults standardUserDefaults] setObject:dict forKey:kSAInfoKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [[EMClient sharedClient] loginWithUsername:self.model.wxOpenId
                                      password:@"123456"
                                    completion:^(NSString *aUsername, EMError *aError) {
                                        if (!aError) {
                                            [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
                                        } else {
                                            NSLog(@"登录失败");
                                        }
                                    }];
}

//退出登录
- (void)logoutWithComeBack:(requestSuccess)requestSuccess
{
    [SAHttpApi requestLogOutWithPhone:self.model.phone WithComeBack:requestSuccess];
}

-(void)messagesDidReceive:(NSArray *)aMessages
{
    for (EMMessage *message in aMessages)
    {
        if ([message.ext[@"parentType"] integerValue] != 1)
        {
            continue;
        }
        
        RLMRealm *realm = [RLMRealm defaultRealm];
        
        [realm beginWriteTransaction];
        SARealmMessageModel *model = [[SARealmMessageModel alloc] init];
        model.text = message.ext[@"content"][@"text"];
        model.type = message.ext[@"content"][@"type"];
        model.replyTo = message.ext[@"content"][@"replyTo"];
        model.userId = message.ext[@"content"][@"userId"];
        model.src = message.ext[@"content"][@"src"];
        model.duration = message.ext[@"content"][@"duration"];
        model.bigSrc = message.ext[@"content"][@"bigSrc"];
        model.url = message.ext[@"content"][@"url"];
        model.desc = message.ext[@"content"][@"desc"];
        model.time = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
        
        [realm commitWriteTransaction];
        
    }
    
}
@end
